<template>
  <div class="education-analysis">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
        </div>
      </template>
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="城市">
          <el-select v-model="filterForm.city" placeholder="请选择城市" clearable>
            <el-option label="北京" value="北京" />
            <el-option label="上海" value="上海" />
            <el-option label="广州" value="广州" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">应用筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 学历分布 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学历分布饼图</span>
            </div>
          </template>
          <div ref="educationPieChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学历分布柱状图</span>
            </div>
          </template>
          <div ref="educationBarChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学历/岗位类型关联分析 -->
<!--    <el-card class="chart-card">-->
<!--      <template #header>-->
<!--        <div class="card-header">-->
<!--          <span>学历/岗位类型关联分析</span>-->
<!--        </div>-->
<!--      </template>-->
<!--      <div ref="educationScatterChart" class="chart"></div>-->
<!--    </el-card>-->

    <!-- 智能感知 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>智能感知</span>
          <el-button
            type="primary"
            :loading="adviceLoading"
            :disabled="adviceLoading"
            @click="fetchAdvice"
            class="advice-btn"
          >
            <el-icon v-if="!adviceLoading" style="margin-right:4px;"><Lightning /></el-icon>
            {{ adviceLoading ? '生成中...' : '获取智能建议' }}
          </el-button>
          <span v-if="adviceLoading" class="advice-tip">智能建议生成可能需要几秒钟，请耐心等待...</span>
        </div>
      </template>
      <div v-loading="adviceLoading" class="advice-content">
        <div v-if="overallAdvice" class="overall-advice" v-html="overallAdvice"></div>
        <div v-for="(point, index) in advicePoints" :key="index" class="advice-point">
          <h3 v-html="point.title"></h3>
          <div v-html="point.content" class="advice-text"></div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Lightning } from '@element-plus/icons-vue'

// 筛选表单
const filterForm = ref({
  city: ''
})

// 图表实例
let educationPieChartInstance = null
let educationBarChartInstance = null
let educationScatterChartInstance = null

// 图表DOM引用
const educationPieChart = ref(null)
const educationBarChart = ref(null)
const educationScatterChart = ref(null)

// 智能感知相关
const adviceLoading = ref(false)
const overallAdvice = ref('')
const advicePoints = ref([])

// 获取学历分布数据
const fetchEducationDistribution = async () => {
  try {
    const params = new URLSearchParams()
    if (filterForm.value.city) {
      params.append('city', filterForm.value.city)
    }

    const response = await axios.get(`http://localhost:8081/api/education/distribution?${params.toString()}`)
    if (response.data.code === 200) {
      initEducationPieChart(response.data.data)
      initEducationBarChart(response.data.data)
      initEducationScatterChart(response.data.data)
    }
  } catch (error) {
    ElMessage.error('获取学历分布数据失败')
  }
}

// 初始化学历分布饼图
const initEducationPieChart = (data) => {
  if (!educationPieChart.value) return

  educationPieChartInstance = echarts.init(educationPieChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const total = data.reduce((sum, item) => sum + item.count, 0)
        const percentage = ((params.value / total) * 100).toFixed(2)
        return `${params.name}<br/>职位数量: ${params.value}<br/>占比: ${percentage}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '学历分布',
        type: 'pie',
        radius: '50%',
        data: data.map(item => ({
          name: item.education,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  educationPieChartInstance.setOption(option)
}

// 初始化学历分布柱状图
const initEducationBarChart = (data) => {
  if (!educationBarChart.value) return

  educationBarChartInstance = echarts.init(educationBarChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const total = data.reduce((sum, item) => sum + item.count, 0)
        const percentage = ((params[0].value / total) * 100).toFixed(2)
        return `${params[0].name}<br/>职位数量: ${params[0].value}<br/>占比: ${percentage}%`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.education),
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '职位数量'
    },
    series: [
      {
        name: '职位数量',
        type: 'bar',
        data: data.map(item => item.count),
        label: {
          show: true,
          position: 'top'
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  educationBarChartInstance.setOption(option)
}

// 初始化学历/岗位类型关联散点图
const initEducationScatterChart = (data) => {
  if (!educationScatterChart.value) return

  educationScatterChartInstance = echarts.init(educationScatterChart.value)
  
  // 模拟岗位类型数据（实际项目中应该从后端获取）
  const jobTypes = ['技术', '产品', '设计', '运营', '市场', '销售']
  const scatterData = data.flatMap(item => {
    return jobTypes.map(type => {
      // 根据学历和岗位类型生成模拟数据
      const baseCount = item.count
      const randomFactor = Math.random() * 0.5 + 0.5 // 0.5-1之间的随机数
      return {
        name: `${item.education}-${type}`,
        value: [
          jobTypes.indexOf(type),
          data.indexOf(item),
          Math.round(baseCount * randomFactor)
        ]
      }
    })
  })

  const option = {
    tooltip: {
      formatter: function(params) {
        return `${params.data.name}<br/>职位数量: ${params.data.value[2]}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: jobTypes,
      name: '岗位类型'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.education),
      name: '学历要求'
    },
    series: [
      {
        name: '职位分布',
        type: 'scatter',
        data: scatterData,
        symbolSize: function(data) {
          return Math.sqrt(data[2]) * 2
        },
        itemStyle: {
          color: function(params) {
            const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
            return colors[params.data.value[0]]
          }
        }
      }
    ]
  }
  educationScatterChartInstance.setOption(option)
}

// 获取智能建议
const fetchAdvice = async () => {
  try {
    adviceLoading.value = true
    const response = await axios.get('http://localhost:8081/api/advice/education')
    if (response.data.code === 200) {
      overallAdvice.value = response.data.data.overallAdvice
      advicePoints.value = response.data.data.advicePoints
    }
  } catch (error) {
    ElMessage.error('获取智能建议失败')
  } finally {
    adviceLoading.value = false
  }
}

// 处理筛选
const handleFilter = () => {
  fetchEducationDistribution()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    city: ''
  }
  handleFilter()
}

// 处理窗口大小变化
const handleResize = () => {
  educationPieChartInstance?.resize()
  educationBarChartInstance?.resize()
  educationScatterChartInstance?.resize()
}

onMounted(() => {
  fetchEducationDistribution()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  educationPieChartInstance?.dispose()
  educationBarChartInstance?.dispose()
  educationScatterChartInstance?.dispose()
})
</script>

<style scoped>
.education-analysis {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select) {
  width: 180px;
}

:deep(.el-form-item__content) {
  flex-wrap: wrap;
}

.advice-content {
  padding: 20px;
}

.overall-advice {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  line-height: 1.8;
}

.advice-point {
  margin-bottom: 30px;
}

.advice-point:last-child {
  margin-bottom: 0;
}

.advice-point h3 {
  margin-bottom: 15px;
  color: #409EFF;
}

.advice-text {
  line-height: 1.8;
  color: #606266;
}

.advice-text :deep(p) {
  margin-bottom: 10px;
}

.advice-text :deep(ul) {
  padding-left: 20px;
  margin-bottom: 10px;
}

.advice-text :deep(li) {
  margin-bottom: 5px;
}

.advice-text :deep(strong) {
  color: #303133;
}

.advice-text :deep(h3) {
  color: #409EFF;
  margin: 20px 0 10px;
}

.advice-text :deep(hr) {
  margin: 20px 0;
  border: none;
  border-top: 1px solid #ebeef5;
}

.advice-btn {
  border-radius: 24px;
  font-weight: 600;
  background: linear-gradient(90deg, #409EFF 0%, #36D1DC 100%);
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  transition: all 0.2s;
  padding: 0 24px;
}
.advice-btn:hover {
  filter: brightness(1.08);
  box-shadow: 0 4px 16px rgba(64,158,255,0.15);
}
.advice-tip {
  margin-left: 16px;
  color: #909399;
  font-size: 14px;
  vertical-align: middle;
}
</style> 